//
//  FavoritesViewController.swift
//  Automobile
//
//  Created by erkebulan elzhan on 7/26/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit
import SnapKit


class FavoritesViewController: UIViewController, Alertable {
    
    // MARK: - Outlets
    
    lazy private var tableView: UITableView = {
        let table = UITableView()
        table.register(PostCell.self, forCellReuseIdentifier: "postCell")
        table.backgroundColor = .rgb(229, 229, 229)
        table.delegate = self
        table.dataSource = self
        table.tableFooterView = UIView()
        table.separatorStyle = .none
        table.addSubview(refreshControl)
        table.showsVerticalScrollIndicator = false
        return table
    }()
    
    private lazy var spinnerView = SpinnerView()
    
    private lazy var emptyView: EmptyView = {
        let emptyView = EmptyView()
        emptyView.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: 200)
        return emptyView
    }()
    
    private lazy var refreshControl: UIRefreshControl = {
        let refControl = UIRefreshControl()
        refControl.addTarget(self, action: #selector(doRefresh), for: .valueChanged)
        return refControl
    }()
    
    
    // MARK: - Properties
    
    private var viewModel = FavModel()
    private var isLoading = false {
        didSet {
            view.isUserInteractionEnabled = !isLoading
            isLoading ? spinnerView.startAnimating() : spinnerView.stopAnimating()
        }
    }
    
    // for pagination
    private var nextPage: String?
    
    // MARK: - Actions
    
    // dismiss current view controller
    @objc private func goBack (sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc private func doRefresh () {
        self.loadPosts()
    }
    
    // MARK: - Life-Cycle of App
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        self.setUpNav()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.addViews()
        self.loadPosts()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        self.navigationController?.navigationBar.isHidden = true
        self.tabBarController?.tabBar.isHidden = false
    }
}



// MARK: - Methods

extension FavoritesViewController {
    
    // MARK: - Network
    
    private func loadPosts (request: URLRequest?=nil) {
        self.isLoading = true
        
        viewModel.getPosts(request: request) { (result) in
            self.isLoading = false
            self.refreshControl.endRefreshing()
            switch result {
            case .failure(let error):
                switch error {
                case .general:
                    self.showAlert("Упс", "Неизвестная ошибка")
                case .parameter(let message):
                    self.showAlert("Упс", message)
                }
            case .success(let posts):
                if posts.results.count == 0 {
                    self.tableView.tableHeaderView = self.emptyView
                } else {
                    self.tableView.tableHeaderView = nil
                }
                self.nextPage = posts.next
                self.tableView.reloadData()
            }
        }
    }
    
    // MARK: - UI
    
    private func addViews () {
        self.view.addSubview(tableView)
        self.view.addSubview(spinnerView)
        tableView.snp.makeConstraints { (make) in
            make.leading.trailing.bottom.top.equalTo(view.safeAreaLayoutGuide)
        }
        spinnerView.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.height.equalToSuperview()
        }
    }
    
    private func setUpNav () {
        self.view.backgroundColor = .white
        self.navigationController?.navigationBar.isHidden = false
        self.navigationController?.navigationBar.defaultNavBar()
        
        let backIcon = UIImage(named: "cancel")
        let backButton = UIBarButtonItem(image: backIcon, landscapeImagePhone: backIcon, style: .plain, target: self, action: #selector(goBack(sender:)))
        backButton.tintColor = .greyColor
        
        self.navigationItem.simpleNavBar(title: "Избранные", backButton: backButton)
    }
}

// MARK: - UI Table View

extension FavoritesViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let postVC = MainViewController()
        postVC.setProps(post: self.viewModel.favorites[indexPath.row].advert)
        self.navigationController?.pushViewController(postVC, animated: true)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.favorites.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "postCell") as! PostCell
        cell.selectionStyle = .none
        let postModel = PostModel(post: viewModel.favorites[indexPath.row].advert)
        cell.configure(data: postModel, index: indexPath.row)
        
        let messageTap = GestureWithTag(target: self, action: #selector(sendMessage(sender:)))
        messageTap.tag = indexPath.row
        cell.messageBtn.addGestureRecognizer(messageTap)
               
        let contactTap = GestureWithTag(target: self, action: #selector(onCall(sender:)))
        contactTap.tag = indexPath.row
        cell.callBtn.addGestureRecognizer(contactTap)
        
        cell.likeButton.tag = indexPath.row
        cell.likeButton.addTarget(self, action: #selector(onLikeClick(sender:)), for: .touchUpInside)
        
        cell.selectionStyle = .none
        return cell
    }
    
    // Infinite scroll
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        let offsetY = scrollView.contentOffset.y
        let contentHeight = scrollView.contentSize.height
        
        if offsetY > contentHeight - scrollView.frame.size.height {
            if let next = nextPage {
                let request = URLRequest(url: URL(string: next)!)
                self.loadPosts(request: request)
            }
        }
    }
}


// MARK: - Cell Actions

extension FavoritesViewController {
    
    @objc private func onLikeClick (sender: UIButton) {
        let backend = Backend()
        let isRemove = self.viewModel.favorites[sender.tag].advert.isLiked
        let postId = self.viewModel.favorites[sender.tag].advert.id
        
        backend.addToFavorites(advertID: postId, isRemove: isRemove) { (isSuccess, errorMessage) in
            if isSuccess {
                self.viewModel.favorites[sender.tag].advert.isLiked.toggle()
                self.tableView.reloadData()
            } else {
                self.showAlert("Упс...", errorMessage!)
            }
        }
    }
    
    @objc private func onCall (sender: GestureWithTag) {
        let post = self.viewModel.favorites[sender.tag].advert
        if let number = post.contactNumbers?.first {
            if let url = URL(string: "tel://\(number)") {
                if #available(iOS 10, *) {
                    UIApplication.shared.open(url, options: [:], completionHandler:nil)
                } else {
                    UIApplication.shared.openURL(url)
                }
            } else {
                self.showAlert("Упс...", "У нас нет контактного номера данного пользователя")
            }
        } else {
            self.showAlert("Упс...", "У нас нет контактного номера данного пользователя")
        }
    }
    
    @objc private func sendMessage (sender: GestureWithTag) {
        let post = self.viewModel.favorites[sender.tag].advert
        let commentsVC = CommentsViewController()
        commentsVC.advertID = post.id
        self.navigationController?.pushViewController(commentsVC, animated: true)
    }
}

